import { useRouter } from '@/router/hooks';
import {
  DuplicateCollection,
  KnowCollection,
  KnowMenu,
  KnowSimilarityCollection,
} from '@/types/know/know';
import { Button, Divider, message, Popconfirm, Tooltip } from 'antd';
import { useMemo, useState } from 'react';
import SubPageHeader from '../../components/SubPageHeader';
import SubPageContent from '../../components/SubPageContent';
import PaginationTable from '../../components/PaginationTable';
import knowService from '@/api/services/knowService';
import dayjs from 'dayjs';
import FileCompareModal from './components/FileCompareModal';
import '@/pages/know-gov/styles/know-gov.scss';
import { InfoCircleOutlined } from '@ant-design/icons';
import React from 'react';
import datasetService from '@/api/services/datasetService';
import ChangeExpiredTimeModal from './components/ChangeExpiredTimeModal';
import Tip from '@/components/tip/Tip';
import SubPageTabs from '../../components/SubPageTabs';
import { SvgIcon } from '@/components/icon';

const Document = ({ onBack }: { onBack: () => void }) => {
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [searchText, setSearchText] = useState('');
  const [fileCompareModalVisible, setFileCompareModalVisible] = useState(false);
  const [changeExpiredTimeModalVisible, setChangeExpiredTimeModalVisible] = useState(false);
  const [currentCollection, setCurrentCollection] = useState<
    KnowSimilarityCollection | KnowCollection | null
  >(null);
  const router = useRouter();
  const [refershExpire, setRefershExpire] = useState(0);
  const [refreshSimilarity, setRefreshSimilarity] = useState(0);

  const refreshData = () => {
    switch (selectedIndex) {
      case 0:
        setRefreshSimilarity((prev) => prev + 1);
        break;
      case 1:
        setRefershExpire((prev) => prev + 1);
        break;
      default:
        break;
    }
  };

  const completed = () => {
    setFileCompareModalVisible(false);
    setCurrentCollection(null);
  };

  const updateCurrentCollection = (collection: KnowSimilarityCollection | KnowCollection) => {
    if (
      collection.isDeleted ||
      (collection?.duplicateList && collection?.duplicateList.length <= 0)
    ) {
      setCurrentCollection(null);
      setFileCompareModalVisible(false);
      refreshData();
    } else {
      setCurrentCollection(collection);
    }
  };

  const onHandle = (item: KnowSimilarityCollection) => {
    setCurrentCollection(item);
    setFileCompareModalVisible(true);
  };

  const onCompareModalCancel = () => {
    setFileCompareModalVisible(false);
    setCurrentCollection(null);
  };

  const onExpiredHandle = (item: KnowCollection) => {
    setCurrentCollection(item);
    setChangeExpiredTimeModalVisible(true);
  };

  const changeExpiredTimeConfirm = async (expiredTime: string) => {
    try {
      await knowService.postUpdateExpired({
        collection_id: currentCollection?._id!,
        expired_time: expiredTime,
      });
      message.success('修改成功');
      setChangeExpiredTimeModalVisible(false);
      refreshData();
    } catch (error) {
      console.error(error);
    }
  };

  const delExpireCollection = async (item: KnowCollection) => {
    try {
      console.log(3, item);

      // await datasetService.deleteDatasetCollection(item._id);
      await datasetService.deleteDatasetFile({
        // fileIds: [item?.fileId],
        ids: [item?._id],
      });
      message.success('删除成功');
      refreshData();
    } catch (error) {
      console.error(error);
    }
  };

  const dcColumns = [
    {
      title: '文件名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '文档所属',
      width: '10%',
      dataIndex: 'datasetName',
      key: 'datasetName',
      render: (datasetName: string) => {
        return <div>{datasetName}</div>;
      },
    },
    {
      title: '状态',
      width: '10%',
      dataIndex: 'status',
      key: 'status',
      render: (_, record: KnowSimilarityCollection) => {
        const dealLength = record?.duplicateList?.filter((item) => item.status !== 0)?.length || 0;
        const base = record.status === 0 ? 0 : 1;
        const total = record?.duplicateList?.length + 1 || 0;
        return <div>{`${dealLength + base}/${total}`}</div>;
      },
    },
    {
      title: '相似文档数',
      width: '10%',
      dataIndex: 'duplicateList',
      key: 'duplicateList',
      render: (duplicateList: []) => {
        return (
          <div>
            {duplicateList?.length || 0}{' '}
            <Tooltip
              // placement="bottomRight"
              className="cursor-pointer"
              rootClassName="know-gov-document-tooltip"
              title={() => {
                return (
                  <div style={{ maxHeight: '400px', whiteSpace: 'pre-wrap', overflow: 'auto' }}>
                    <div className="text-base">相似文档数：({duplicateList?.length || 0})</div>
                    <div className="grid grid-cols-4 gap-2">
                      <div className="col-span-2">文档</div>
                      <div>相似度</div>
                      <div>状态</div>
                      {duplicateList?.map((item: DuplicateCollection, index: number) => (
                        <React.Fragment key={index}>
                          <div className="col-span-2 flex flex-col">
                            <div>{item.name}</div>
                            <div className="text-nowrap text-xs text-[#A5A9BB]">
                              知识库：{item.datasetName}
                            </div>
                          </div>
                          <div>{Number((item.similarity * 100).toFixed(2))}%</div>
                          <div>{item.status === 0 ? '未处理' : '已处理'}</div>
                        </React.Fragment>
                      ))}
                    </div>
                  </div>
                );
              }}
            >
              <InfoCircleOutlined />
            </Tooltip>
          </div>
        );
      },
    },
    {
      title: '操作',
      width: '10%',
      key: 'operation',
      render: (_, record: KnowSimilarityCollection) => (
        <Button size="small" className="ml-auto" type="text" onClick={() => onHandle(record)}>
          <span className="text-primary">
            {' '}
            <SvgIcon icon="message-ic19" size="20" className="mr-1" />
            处理
          </span>
        </Button>
      ),
    },
  ];

  const expiredColumns = [
    {
      title: '文件名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: (
        <div>
          文档所属
          <Tip className="know-gov-tooltip ml-1" title={<div>文档所属知识库</div>} />
        </div>
      ),
      width: '10%',
      dataIndex: 'datasetName',
      key: 'datasetName',
      render: (datasetName: string) => {
        return <div>{datasetName}</div>;
      },
    },
    {
      title: '有效期',
      width: '20%',
      dataIndex: 'expiredTime',
      key: 'expiredTime',
      render: (expiredTime: string) => {
        return <div>{dayjs(expiredTime).format('YYYY-MM-DD HH:mm:ss')}</div>;
      },
    },
    {
      title: (
        <div>
          操作
          <Tip
            className="know-gov-tooltip ml-1"
            title={
              <div>
                <p>处理：修改过期时间，确认修改后，该文件将自动启用。</p>
                <p>
                  删除：删除过期文件，<span className="text-orange">删除后文件不可恢复</span>。
                </p>
              </div>
            }
          />
        </div>
      ),
      width: '10%',
      key: 'operation',
      render: (_, record: KnowCollection) => (
        <div className="ml-auto flex gap-2">
          <Button size="small" type="text" onClick={() => onExpiredHandle(record)}>
            <span className="flex items-center text-primary">
              <SvgIcon icon="message-ic19" size="20" className="mr-1" />
              处理
            </span>
          </Button>
          <Popconfirm
            title={`您确定要删除文件 ${record.name} 吗?`}
            onConfirm={() => {
              delExpireCollection(record);
            }}
            okText="删除"
            cancelText="取消"
          >
            <Button size="small" type="text">
              <span className="flex items-center text-error">
                {' '}
                <SvgIcon icon="message-ic3" size="20" className="mr-1" />
                删除
              </span>
            </Button>
          </Popconfirm>
        </div>
      ),
    },
  ];

  const menus: KnowMenu[] = useMemo(() => {
    return [
      {
        key: 0,
        title: '知识重复',
        children: (
          <PaginationTable
            rowKey="_id"
            columns={dcColumns}
            searchText={searchText}
            api={knowService.getSimilarity}
            refreshKey={refreshSimilarity}
          />
        ),
      },
      // {
      //   key: 1,
      //   title: '知识冲突',
      // },
      {
        key: 1,
        title: '知识老化',
        children: (
          <PaginationTable
            rowKey="_id"
            columns={expiredColumns}
            searchText={searchText}
            api={knowService.getExpired}
            refreshKey={refershExpire}
          />
        ),
      },
    ];
  }, [searchText, refershExpire, refreshSimilarity, selectedIndex]);

  return (
    <div className="flex h-full flex-col overflow-hidden pb-6">
      <SubPageHeader
        menus={menus}
        title="知识处理"
        onBack={onBack}
        selectedIndex={selectedIndex}
        onChangeIndex={(index) => setSelectedIndex(index)}
        onSearchTextChanged={setSearchText}
      />
      <SubPageTabs
        menus={menus}
        title="知识处理"
        onBack={onBack}
        selectedIndex={selectedIndex}
        onChangeIndex={(index) => setSelectedIndex(index)}
        onSearchTextChanged={setSearchText}
      />

      <SubPageContent menus={menus} selectedIndex={selectedIndex} />
      <FileCompareModal
        open={fileCompareModalVisible}
        collection={(currentCollection as KnowSimilarityCollection)!}
        setCollection={updateCurrentCollection}
        onCancel={onCompareModalCancel}
        refresh={refreshData}
        completed={completed}
      />
      <ChangeExpiredTimeModal
        open={changeExpiredTimeModalVisible}
        defaultDate={currentCollection?.expiredTime}
        onCancel={() => {
          setChangeExpiredTimeModalVisible(false);
        }}
        onConfirm={changeExpiredTimeConfirm}
      />
    </div>
  );
};

export default Document;
